﻿package test;

import java.lang.reflect.Array;
import java.util.Arrays;

/**
 * 反射二:动态扩充数组
 * */
public class LangDemo3 {
	public static void main(String[] args) throws Exception {
		int[] nums = {1,2,3,4,5};
		String[] names = {"Merry","Jack","Linda"};
		int[] newNums = (int[]) enlargeArrays(nums,7);
		String[] newNames = (String[]) enlargeArrays(names,7);
		System.out.println(Arrays.toString(newNums)+"\n"+Arrays.toString(newNames));
	}

	private static Object enlargeArrays(Object nums,int newCapacity) throws Exception {
		Class<?> c = nums.getClass();
		Object newArray = null;
		if(c.isArray()){
			//创建新数组[Array是动态创建和访问数组的工具类]
			newArray = Array.newInstance(c.getComponentType(),newCapacity);
			//复制原数据到新数组
			System.arraycopy(nums, 0, newArray, 0, Array.getLength(nums));
		}
		return newArray;
	}
}
